<template>
  <div class="detail" :style="{minWidth:state.type == 1?'700px':'560px',maxWidth:state.type == 1?'700px':'560px'}">
    <div class="detailBox">
      <!-- 顶部 -->
      <div class="topBox" :style="{width:state.type == 1?'29%':'25%'}">
        <div style="display: flex;justify-content: space-between;">
          <img src="./chatCom/logo.svg" alt="" />
          <img @click="hisShowClick(1)" v-if="state.type == 2" src="./chatCom/shou.svg" alt="" />
          <img @click="hisShowClick(2)" v-if="state.type == 1" style="margin-left: 10px;" src="./chatCom/zhan.svg"
            alt="" />
        </div>
      </div>
      <!-- 内容区 -->
      <div class="detailBoxdesc">
        <!-- 左侧 -->
        <div :style="{width:state.type == 1 ?'26%':'0'}" class="leftBox" v-if="state.type == 1"
          :class="state.type == 1?'leave-active':'enter-active'">
          <div>
            <span class="btntopBox" @click="newChartClick">
              <span class="btnBoxjb">
                <span class="jbText" style="display: flex;justify-content: center;align-items: center;"><img
                    src="./chatCom/plus.svg" alt=""><span>新对话</span></span>
              </span>
            </span>
          </div>
          <div class="hisSelBox">
            <div class="typeBox">
              近七天
            </div>
            <div v-for="item in state.sessionsList">
              <div @mouseenter="leftBoxenter(item)" @mouseleave="leftBoxleave(item)" @click="listBoxClick(item)">
                <el-tooltip placement="right-end" effect="light">
                  <template #content>
                    <span class="listBoxremove" @click.stop="listBoxremoveClick(item)">
                      <img src="./chatCom/shanchu.svg" alt="">删除</span> </template>
                  <span
                    :class="state.sessionValue==item.session_id?'listBox active':'listBox'">{{ item.first_user_query }}</span>
                </el-tooltip>
              </div>
            </div>
          </div>
        </div>
        <!-- 右侧 -->
        <div :style="{width:state.type == 1 ?'74%':'100%',padding:state.type == 1 ?'0':'',
          justifyContent:state.valueDis == ''&&(state.sessionsDetailList.length==0||state.chartList.length==0)?'':'start'
        }" class="rightBox">
          <!-- 会话聊天记录 -->
          <div class="chartList" ref="containerRef"
            :style="{height:state.valueDis == ''&&state.sessionsDetailList.length==0?0:'50vh'}">
            <!-- 详情展示 -->
            <div>
              <div v-for="(item,index) in state.sessionsDetailList" class="chartListBox">
                <div>
                  <div class="qusBox">
                    <span>{{ item[0].content}}</span>
                  </div>
                  <div class="ansBox">
                    <span class="span">
                      <img src="./chatCom/jiqi.svg" alt="">
                      <MdPreview class="thinkBox" style="--md-color: rgba(62, 70, 79, .6);"
                        :previewOptions="state.previewOptions" v-model="item[2].content"></MdPreview>
                      <MdPreview :previewOptions="state.previewOptions" v-model="item[1].content"></MdPreview>
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <!-- 会话列表展示 -->
            <div>
              <div v-for="(item,index) in state.chartList" class="chartListBox">
                <div class="qusBox">
                  <span>{{ item.msg}}</span>
                </div>
                <div class="ansBox">
                  <span class="span">
                    <img src="./chatCom/jiqi.svg" alt="">
                    <span @click="thinkBoxShowhideClick(item)"
                      style="font-size: 14px;margin-top: 10px;color: #3f4a54;margin-bottom: 4px;">
                      深度思考
                      <svg-icon icon-class="xia" v-if="!item.show" />
                      <svg-icon icon-class="shang" v-else /></span>
                    <MdPreview v-if="!item.show&&item.subDesc" class="thinkBox" :previewOptions="state.previewOptions"
                      v-model="item.subDesc">
                    </MdPreview>
                    <MdPreview :previewOptions="state.previewOptions" v-model="item.data">
                    </MdPreview>
                  </span>
                </div>
              </div>
            </div>
            <!-- 当前会话效果展示 -->
            <div class="chartListBox" v-if="state.showList">
              <div class="qusBox">
                <span>{{ state.valueDis}}</span>
              </div>
              <div class="ansBox">
                <span class="span">
                  <img src="./chatCom/jiqi.svg" alt="">
                  <p v-if="state.displayedText != ''" style="display: flex;flex-direction: column;font-size: 14px;">
                    <span v-if="state.btnelBoxShow==1">
                      <span
                        style="background-color: rgba(0, 0, 0, .1);display: inline-block;padding: 4px;border-radius: 4px;">深度{{ state.displayedText }}
                      </span>
                      <svg-icon icon-class="xia" />
                    </span>
                    <svg-icon class="donut" icon-class="jiazaizhong" />
                  </p>
                  <MdPreview v-if="state.thinkData.length>0" class="thinkBox" :previewOptions="state.previewOptions" 
                  v-model="state.thinkData[0]">
                  </MdPreview>
                  <MdPreview :previewOptions="state.previewOptions" v-model="state.data"></MdPreview>
                </span>
              </div>
            </div>
          </div>
          <!-- 输入框展示 -->
          <div class="inputBoxdetail" v-if="!inputBoxchartShow">
            <div class="title jbText" v-if="state.valueDis == ''">你好，我是小恒。<br />你的超级助手已上线！</div>
            <div class="inputDesc" style="height: 116px !important;">
              <el-input class="inputBox" v-model="state.value" type="textarea" @keyup.enter.native="sendTextClick(state.value)"
                 placeholder="你可以问我任何问题">
              </el-input>
              <div class="btnBox">
                <span style="display: flex;">
                  <span @click="btnelBoxClick(1)" :class="state.btnelBoxShow==1?'btnelBox active':'btnelBox'">
                    <img v-if="state.btnelBoxShow==1" src="./chatCom/shendu.svg" alt="">
                    <img v-else src="./chatCom/nao.svg" alt="">
                    <span>深度思考</span></span>
                  <span @click="btnelBoxClick(2)" :class="state.btnelBoxShow==2?'btnelBox active':'btnelBox'">
                    <img v-if="state.btnelBoxShow==2" src="./chatCom/liandiqiu.svg" alt="">
                    <img v-else src="./chatCom/diqiu.svg" alt="">
                    <span>联网搜索</span>
                  </span>
                </span>
                <span style="display: flex;align-items: center;">
                  <el-upload class="upload-demo" style="margin-top:6px" action :show-file-list="false"
                    :http-request="uploadHttpRequestAdd">
                    <img src="./chatCom/lian.svg" alt="">
                  </el-upload>
                  <el-button v-if="!state.btnloading" :disabled="state.value==''" @click.stop="sendTextClick(state.value)"
                    size="mini" style="width: 30px;height: 30px;" type="primary" circle>
                    <img src="./chatCom/arrow.svg" alt="">
                  </el-button>
                  <el-button v-else size="mini" type="primary" circle
                    style="display: flex;align-items: center;text-align: center;">
                    <span style="width: 14px;height: 14px;background-color: #fff;display: inline-block;"></span>
                  </el-button>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="footerBox" :style="{justifyContent:state.type == 1?'flex-start':'center'}">
        <img style="margin-left: 10px;" src="./chatCom/deep.svg" alt="" />
      </div>
    </div>
  </div>
</template>
<script setup>
  import axios from 'axios';
  import {
    MdPreview
  } from 'md-editor-v3';
  import 'md-editor-v3/lib/preview.css';
  import {
    reactive,
    nextTick,
    onUpdated,
    ref
  } from 'vue';
  const containerRef = ref(null)
  const {
    proxy
  } = getCurrentInstance();
  const emits = defineEmits([''])
  const props = defineProps({
    newEvent: {
      type: String,
      default: undefined,
    },
    displayedText: {
      type: String,
      default: '',
    },
    valueDis: {
      type: String,
      default: '',
    },
    inputBoxchartShow: {
      type: Boolean,
      default: false,
    },
    fromInputCombtnelBoxShow: {
      type: Number,
      default: undefined,
    }
  });
  const state = reactive({
    previewOptions: {
      hljs: {
        // 自动展开代码块
        autoDetectCodeBlock: true,
      },
      codeBlock: {
        expand: true, // 确保代码块一直展开
      },
    },
    loadingInterval: null,
    type: 2,
    value: '',//输入框内容
    valueDis: '',//比较输入框内容
    data: '', // 要解析的markdown语法的内容
    displayedText: '',//提示问题描述
    chartList: [],//会话列表展示
    thinkData: '',//思考内容展示
    btnloading: false,//会话提交按钮加载效果
    showList: false,//会话流是否完成加载控制当前会话和上次会话列表展示
    btnelBoxShow: undefined,//深度和联网按钮选择属性
    sessionsList: [],//左侧历史列表展示
    sessionsDetailList: [],//点击左侧历史列表数据展示右侧详情
    sessionValue: undefined,//左侧历史列表id
  })

  function newChartClick() {
    state.displayedText = ''
    state.valueDis = ''
    state.data = ''
    state.value = ''
    state.chartList = []
    emits('sendTextClickdrawernew', '')
  }
  // 是否展示左侧历史列表
  function hisShowClick(type) {
    state.type = type
  }
  // 提交会话按钮事件
  function sendTextClick(value) {
    if(value.replace(/\r|\n/ig, "") ==''){
      state.value=''
      proxy.$modal.msgWarning('请输入您的问题!');
    }else{
      emits('sendTextClickdrawer', '')
      state.data = '' //清空上一次数据答案
      state.thinkData = '' //清空上一轮思考
      state.valueDis = value
      // 定时器 loading 效果
      let count = 0;
      state.loadingInterval = setInterval(() => {
        state.btnloading = true
        count++;
        if (count > 3) {
          count = 0;
        }
        switch (count) {
          case 0:
            state.displayedText = "加载思考中";
            break;
          case 1:
            state.displayedText = "加载思考中.";
            break;
          case 2:
            state.displayedText = "加载思考中..";
            break;
          case 3:
            state.displayedText = "加载思考中...";
            break;
        }
      }, 500);
      fetchDeepSeekData(state.loadingInterval)
    }
  }
  // 会话发送接口请求
  async function fetchDeepSeekData() {
    state.showList = true
    await axios.post('/chat-api/sessions', {
      user_id: 1,
      platform: 'safety'
    }).then(async res => {
      if (res.data.status == 'success') {
        await axios({
          url: '/chat-api/chat',
          method: 'post',
          data: {
            msg: state.value.replace(/\r|\n/ig, ""),
            modelType: 'local',
            session_id: res.data.session_id
          },
          onDownloadProgress: ({
            event
          }) => {
            const xhr = event.target;
            const {
              responseText
            } = xhr;
            const thinkTagRegexNo = /<think>[\s\S]*?<\/think>/g;
            let chunk = responseText;
            // 正则表达式匹配 <think> 标签及其内容
            const thinkTagRegex = /<think>([\s\S]*?)<\/think>/g;
            // 提取所有匹配的 <think> 标签内容
            const matches = [];
            let match;
            while ((match = thinkTagRegex.exec(chunk)) !== null) {
              matches.push(match[1].trim()); // 提取内容并去除前后空白
            }
            if (matches.length > 0) {
              state.thinkData = matches
            } else {
              state.thinkData = [chunk]
            }
            if (thinkTagRegexNo.test(chunk)) {
              clearInterval(state.loadingInterval);
              const contentWithoutThinkTags = chunk.replace(thinkTagRegexNo, '').trim();
              try {
                const data = contentWithoutThinkTags;
                state.data = (data ?? '');
                state.displayedText = ''
                state.btnloading = false
              } catch (error) {
                state.data = (error.message);
              }
            } else {
              state.btnloading = true
            }
          }
        }).then(response => {
          // 推流完成
          state.showList = false
          nextTick(() => {
            state.chartList.push({
              msg: state.valueDis,
              subDesc: state.thinkData[0],
              data: state.data
            })
          })
        }).catch((error) => {
          // 接口返回出错
          clearInterval(state.loadingInterval)
          state.thinkData=[error.response.data.error]
          state.displayedText = ''
          state.btnloading = false
        });
      }
    })
    emits('sendInputBoxbtnloading', state.btnloading)
  }
  // 上传按钮事件
  function uploadHttpRequestAdd(data) {
    const formData = new FormData();
    formData.append("file", data.file);
    axios.post('/chat-api/upload', formData).then(res => {})
  }
  // 深度和联网按钮展示
  function btnelBoxClick(type) {
    state.btnelBoxShow = type
  }
  /**
   * 
   * @param 左侧菜单操作
   */
  // 左侧删除鼠标悬浮出现
  function leftBoxenter(item) {
    item.show = true
    state.sessionValue = item.session_id
  }
  // 左侧删除鼠标悬浮消失
  function leftBoxleave(item) {
    item.show = false
    state.sessionValue = item.session_id
  }
  //点击删除左侧列表
  function listBoxremoveClick(item) {
    axios.post('/chat-api/sessions/delete', {
      session_id: item.session_id
    }).then(res => {
      proxy.$modal.msgSuccess(res.data.message);
      getHisList()
    })
  }
  // 点击历史会话查看详情
  function listBoxClick(item) {
    state.sessionValue = item.session_id
    axios.post('/chat-api/session/dialogs/list', {
      session_id: item.session_id
    }).then(res => {
      state.sessionsDetailList = res.data.sessions
      state.chartList = []
      containerRef.value.scrollTop = 0
    })
  }
  // 获取左侧查看历史列表
  function getHisList() {
    axios.post('/chat-api/sessions/list', {
      "user_id": 1,
      "platform": "safety"
    }).then(res => {
      state.sessionsList = res.data.sessions
    })
  }

  function thinkBoxShowhideClick(item) {
    item.show = !item.show
  }
  getHisList()
  watchEffect(() => {
    // 首页全局触发机器人会话事件
    if (props.newEvent) {
      sendTextClick(props.newEvent)
    }
    if (props.valueDis != '') {
      state.value = props.valueDis
      sendTextClick(props.valueDis)
    }
    if (props.fromInputCombtnelBoxShow) {
      state.btnelBoxShow = props.fromInputCombtnelBoxShow
    }
  })
  onUpdated(() => {
    //在onUpdated函数里面元素变化的时候令scrollTop和scrollHeight相等，这样内容高度增加的时候
    //滚动条能够向下滑动和内容高度相同的距离
    // containerRef.value.scrollTop = containerRef.value.scrollHeight
  })
</script>
<style scoped lang="scss">
:deep(.md-editor){
height: auto;}
  :deep(.md-editor-preview .md-editor-code) {
    width: 100%;
  }

  /* 为代码块添加横向滚动而不是换行 */
  .md-editor-v3-preview .code-wrapper pre {
    white-space: pre;
    overflow-x: auto;
  }

  /* 可选：为代码块添加最大高度和纵向滚动 */
  .md-editor-v3-preview .code-wrapper pre {
    max-height: 400px;
    overflow-y: auto;
  }

  :deep(.md-editor-preview) {
    font-size: 14px;
  }


  // 转圈圈
  @keyframes donut-spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }

  .donut {
    margin-top: -4px;
    width: 26px !important;
    height: 26px !important;
    animation: donut-spin 1.2s linear infinite;
  }

  .listBoxremove {
    display: flex;
    font-size: 12px;
    color: rgba(227, 60, 100, 1);
    border-radius: 12px;
    align-items: center;
    white-space: nowrap;
    padding: 6px;
  }

  .btnelBox {
    border: 1px solid rgba(206, 206, 206, 1);
    border-radius: 18px;
    display: flex;
    align-items: center;
    padding: 6px;
    font-size: 12px;
    margin-right: 10px;
    cursor: pointer;

    img {
      margin-right: 6px;
    }

    &.active {
      background: rgba(42, 130, 228, 0.1) !important;
      color: rgba(42, 130, 228, 1) !important;
      border: 1px solid rgba(42, 130, 228, 0.1);
    }

  }

  .leave-active {
    animation: slidein 0.5s linear reverse;
  }

  .enter-active {
    animation: slideout 0.8s linear;
  }

  @keyframes slidein {
    from {
      transform: translateX(0px);
    }

    to {
      transform: translateX(-30px);
    }
  }

  @keyframes slideout {
    from {
      transform: translateX(-30px);
    }

    to {
      transform: translateX(0px);
    }
  }

  .jbText {
    /*利用background-clip属性实现文字颜色从绿到白的渐变效果*/
    background-image: linear-gradient(90deg, rgba(131, 76, 204, 1) 0%, rgba(42, 130, 228, 1) 100%);
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
  }

  body {
    padding: 0;
    margin: 0;
    position: relative;
  }

  .hljs .language-html {
    font-size: 14px;
    font-weight: 500;
  }

  .hljs pre {
    background-color: #333;
    font-size: 14px;
    font-weight: 500;

  }

  .qusBoxone {
    width: 100%;
    display: flex;
    justify-content: end;
  }

  .chartList {
    max-height: 50vh;
    overflow-y: auto;
    padding: 0 10px;
    width: 100%;
    // max-width: 540px;

    .qusBox {
      width: 100%;
      display: flex;
      justify-content: end;

      span {
        background-color: rgba(239, 246, 255, 1);
        padding: 8px 16px 8px 16px;
        border-radius: 8px;
        text-align: left;
      }
    }

    .ansBox {
      display: flex;
      justify-content: start;
      margin-top: 20px;

      .thinkBox {
        margin-top: 10px;
        border-radius: 8px;
        background: rgba(62, 70, 79, 0.04);
        padding: 0 10px 10px;
      }

      .span {
        display: inline-block;
        position: relative;
        text-align: left;
        padding-left: 30px;

        img {
          width: 30px;
          height: 30px;
          position: absolute;
          left: -4px;
          top: -4px;
          border: 1px solid #f5f5f5;
          background-color: f5f5f5;
          border-radius: 50%;
          padding: 4px;
        }

      }
    }
  }

  .hisSelBox {
    text-align: left;

    .typeBox {
      margin-top: 20px;
      color: rgba(52, 76, 107, 0.4);
      font-size: 14px;
    }

    .listBox {
      display: inline-block;
      padding: 8px 10px;
      color: rgba(62, 70, 79, 1);
      font-size: 14px;
      font-weight: 500;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      width: 100%;
      border-radius: 4px;

      &:hover {
        background-color: rgba(0, 0, 0, .03);
      }

      &.active {
        background-color: rgba(0, 0, 0, .03);
      }
    }
  }

  .btntopBox {
    margin-top: 20px;
    width: 100%;
    padding: 2px;
    display: inline-block;
    height: 35px;
    line-height: 35px;
    border-radius: 20px;
    background: linear-gradient(135.73deg, rgba(172, 51, 193, 1) 0%, rgba(42, 130, 228, 1) 19.52%, rgba(0, 186, 173, 1) 38.96%, rgba(165, 214, 63, 1) 57.85%,
        rgba(255, 141, 26, 1) 73.65%, rgba(255, 168, 13, 1) 87.83%, rgba(170, 0, 255, 1) 100%);

    .btnBoxjb {
      display: inline-block;
      width: 100%;
      padding: 0px 20px;
      height: 31px;
      line-height: 31px;
      border-radius: 20px;
      background-color: #fff;
      white-space: nowrap;
    }
  }

  .btn {
    position: relative;
    padding-left: 30px !important;
    cursor: pointer;

    img {
      position: absolute;
      top: 50%;
      left: 10px;
      transform: translateY(-50%);
      margin-right: 10px;
    }
  }

  .hljs {
    background: rgba(0, 0, 0, 0);
    color: #333;
  }

  .detail {
    /* min-height: 94vh; */
    /* 插件隐藏 */
    background: linear-gradient(135.73deg, rgba(172, 51, 193, 1) 0%,
        rgba(42, 130, 228, 1) 19.52%, rgba(0, 186, 173, 1) 38.96%, rgba(165, 214, 63, 1) 57.85%,
        rgba(255, 141, 26, 1) 73.65%, rgba(255, 168, 13, 1) 87.83%, rgba(170, 0, 255, 1) 100%);
    /* 插件隐藏 */
    border-radius: 36px;
    padding: 4px;
    max-width: 700px;
  }

  .detailBoxdesc {
    height: 85%;
    display: flex;
    justify-content: space-between;

    .leftBox {
      height: 100%;
      padding-left: 20px;
      overflow-y: auto;
    }

    .rightBox {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      margin-top: 20px;
    }
  }

  .detailBox {
    height: 100%;
    position: relative;
    text-align: center;
    backdrop-filter: blur(4px);
    /* 插件隐藏 */
    border-radius: 32px;
    background: rgba(255, 255, 255, 1);
    backdrop-filter: blur(4px);
  }

  .topBox {
    padding: 22px 20px 0;
    width: 31%;
  }

  .title {
    font-size: 32px;
    color: rgba(34, 34, 34, 1);
    margin-bottom: 24px;
    font-weight: 700;
  }

  .inputBoxdetail {
    margin-top: 20px;
    width: 100%;
    padding: 0 30px;
  }

  .inputDesc {
    position: relative;
    height: 116px !important;
  }

  .inputBox {
    border-radius: 24px;
    background: rgba(255, 255, 255, 1);
    border: 1px solid rgba(229, 229, 229, 1);
    box-shadow: 0px 8px 17px rgba(52, 79, 125, 0.08);
    height: 100% !important;
  }

  .btnBox {
    position: absolute;
    left: 16px;
    right: 16px;
    bottom: 6px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .footerBox {
    display: flex;
    align-items: center;
    padding-top: 10px;
  }

  :deep(.el-textarea__inner) {
    border-radius: 24px !important;
    box-shadow: 0px 8px 17px rgba(52, 79, 125, 0.08);
    padding: 20px !important;
    height: 100%;
  }
</style>